
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <mysql/mysql.h>

#include "database.h"

MYSQL *g_conn;
MYSQL_RES *g_res;
MYSQL_ROW g_row;

const char *g_host_name = "localhost";
const char *g_user_name = "root";
const char *g_password = "12345678";
const char *g_db_name = "bus_terminal";
const unsigned int g_db_port = 3306;

void print_mysql_error(const char *msg)
{
    if (msg)
        printf("%s: %s\n", msg, mysql_error(g_conn));
    else
        puts(mysql_error(g_conn));
}

int executesql(const char * sql)
{
    /*query the database according the sql*/
    if (mysql_real_query(g_conn, sql, strlen(sql)))
		print_mysql_error(sql);
        return -1; 

	printf("%s\n", sql);
    return 0;
}


int init_mysql() 
{
    // init the database connection
    g_conn = mysql_init(NULL);

    /* connect the database */
    if(!mysql_real_connect(g_conn, g_host_name, g_user_name, g_password, g_db_name, g_db_port, NULL, 0)) // ????
        return -1;

    if (executesql("set names utf8"))
        return -1;

    return 0;
}

void closedb()
{
	mysql_close(g_conn);
}

int insert_db_bus_connect(const char * ip)
{
	char sql[MAX_BUF_SIZE] = {0};
	char local_date_time[30] = {0};

	time_t timer;

	timer = time(NULL);
	strftime(local_date_time, sizeof(local_date_time), "%Y-%m-%d %H:%M:%S", localtime(&timer));
	sprintf(sql, "INSERT INTO bus_connect  VALUES('%s','%s');",
		ip,local_date_time);
	return executesql(sql);	
}


